<!DOCTYPE html>
<html>
<head>
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?d890b1f16fb364253e79c5bb20225c3a";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


    

    

    
<!-- Baidu Tongji -->
<script>var _hmt = _hmt || []</script>
<script async src="//hm.baidu.com/hm.js?busuanzi_value_site_uv"></script>
<!-- End Baidu Tongji -->




    <meta charset="utf-8">
    <meta name="baidu-site-verification" content="FYMCShbUK8" />
    <meta name="baidu-site-verification" content="ZYRF7OxQRW" />
    <meta name="baidu-site-verification" content="cHSqtjI0PN" />
    <meta name="baidu-site-verification" content="cHSqtjI0PN" />
    <meta name="baidu-site-verification" content="cHSqtjI0PN" />
    
    
    <link rel="canonical" href="https://hhardyy.com/2018/07/10/对象深拷贝与浅拷贝/">
    
    
    <title>对象深拷贝与浅拷贝 | 小方块 - hhardyy.com | 复杂的坑+归其原理+了解实现规则===解决？解决成功：加油解决成功;</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#958e93">
    
    
    <meta name="keywords" content="stringify,深拷贝与浅拷贝,ES6-Object.assign(),递归拷贝,JQ的$.extend,函数库lodash的_.cloneDeep">
    <meta name="description" content="偶然与道友产生了深浅拷贝的异议，所以赶紧补一补习，需要的你也可以看看">
<meta name="keywords" content="stringify,深拷贝与浅拷贝,ES6-Object.assign(),递归拷贝,JQ的$.extend,函数库lodash的_.cloneDeep">
<meta property="og:type" content="article">
<meta property="og:title" content="对象深拷贝与浅拷贝">
<meta property="og:url" content="http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/index.html">
<meta property="og:site_name" content="小方块 - hhardyy.com">
<meta property="og:description" content="偶然与道友产生了深浅拷贝的异议，所以赶紧补一补习，需要的你也可以看看">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://yoursite.com/images/deepcopy/1.JPG">
<meta property="og:image" content="http://yoursite.com/images/deepcopy/2.JPG">
<meta property="og:image" content="http://yoursite.com/images/deepcopy/3.JPG">
<meta property="og:image" content="http://yoursite.com/images/deepcopy/4.JPG">
<meta property="og:image" content="http://yoursite.com/images/deepcopy/5.JPG">
<meta property="og:updated_time" content="2020-01-13T15:30:26.578Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="对象深拷贝与浅拷贝">
<meta name="twitter:description" content="偶然与道友产生了深浅拷贝的异议，所以赶紧补一补习，需要的你也可以看看">
<meta name="twitter:image" content="http://yoursite.com/images/deepcopy/1.JPG">
    
        <link rel="alternate" type="application/atom+xml" title="小方块 - hhardyy.com" href="/atom.xml">
    
    <link rel="shortcut icon" href="/hardyfavicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/paulGraham.jpg)">
      <div class="brand" style="background-color:#4154b2">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">BingZhenhuang</h5>
          <a href="mailto:huangbingzhen@hhardyy.com" title="huangbingzhen@hhardyy.com" class="mail">huangbingzhen@hhardyy.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                所有文章
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/HHardyy" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://gitee.com/hhardyy" target="_blank" >
                <i class="icon icon-lg icon-cloud"></i>
                Gitee
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://juejin.im/user/59a26f926fb9a02487553b04"  >
                <i class="icon icon-lg icon-pencil"></i>
                掘金-圳
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://segmentfault.com/u/hhardyy"  >
                <i class="icon icon-lg icon-comments"></i>
                Segmentfault
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://codepen.io/HHardyy/" target="_blank" >
                <i class="icon icon-lg icon-codepen"></i>
                Codepen
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://www.freecodecamp.cn/hhardyy" target="_blank" >
                <i class="icon icon-lg icon-leaf"></i>
                Freecodecamp
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/友情链接"  >
                <i class="icon icon-lg icon-link"></i>
                友链
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">对象深拷贝与浅拷贝</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">对象深拷贝与浅拷贝</h1>
        <h5 class="subtitle">
            
                <time datetime="2018-07-09T22:58:07.000Z" itemprop="datePublished" class="page-time">
  2018-07-10
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#浅拷贝"><span class="post-toc-number">1.</span> <span class="post-toc-text">浅拷贝</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#深拷贝"><span class="post-toc-number">2.</span> <span class="post-toc-text">深拷贝</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#对象只有一层的话，可以用ES6的Object-assign-，例子还是上面那个"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">对象只有一层的话，可以用ES6的Object.assign()，例子还是上面那个</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#stringify"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">stringify</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#递归拷贝"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">递归拷贝</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#JQ的-extend"><span class="post-toc-number">2.4.</span> <span class="post-toc-text">JQ的$.extend</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#函数库lodash的-cloneDeep"><span class="post-toc-number">2.5.</span> <span class="post-toc-text">函数库lodash的_.cloneDeep</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#封装一个对象拷贝的方法"><span class="post-toc-number">3.</span> <span class="post-toc-text">封装一个对象拷贝的方法</span></a></li></ol>
        </nav>
    </aside>
    
<article id="post-对象深拷贝与浅拷贝"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">对象深拷贝与浅拷贝</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-07-10 06:58:07" datetime="2018-07-09T22:58:07.000Z"  itemprop="datePublished">2018-07-10</time>

            


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <p>偶然与道友产生了深浅拷贝的异议，所以赶紧补一补习，需要的你也可以看看</p>
<p><iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=552716148&auto=0&height=66"></iframe><br><a id="more"></a></p>
<h3 id="浅拷贝"><a href="#浅拷贝" class="headerlink" title="浅拷贝"></a>浅拷贝</h3><p>浅拷贝只复制指向某个对象的指针，而不复制对象本身，新旧对象还是共享同一块内存。但深拷贝会另外创造一个一模一样的对象，新对象跟原对象不共享内存，修改新对象不会改到原<br>对象。<br>举个栗子：假如有两个对象a和b，我想让b对象拥有a对象的属性和方法，然后b对象某些同属性的keyvalue和a不一样，可能会这么写<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> a = &#123;</div><div class="line">name: <span class="string">"hhardyy"</span></div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> b = a;</div><div class="line">b.name = <span class="string">"xiaofangkuai"</span>;</div><div class="line"><span class="built_in">console</span>.log(a.name) <span class="comment">//xiaofangkuai</span></div></pre></td></tr></table></figure></p>
<p>但是这样之后a对象的name也被改变了，举例浅拷贝一个initObj对象，里面有各种属性和方法<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> initObj = &#123;</div><div class="line">    a: <span class="string">"hhardyy"</span>,</div><div class="line">    b: &#123;</div><div class="line">        a: <span class="string">"xiaofangkuai"</span></div><div class="line">    &#125;,</div><div class="line">    c: [<span class="string">"1"</span>, <span class="string">"2"</span>, <span class="string">"3"</span>],</div><div class="line">    d: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">        alert(<span class="string">"hhardyy"</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">clone</span>(<span class="params">obj</span>)</span>&#123;</div><div class="line">    <span class="keyword">var</span> newObj=&#123;&#125;;</div><div class="line">    <span class="keyword">for</span>(key <span class="keyword">in</span> obj)&#123;</div><div class="line">        newObj[key]=obj[key]</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> newObj;</div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> newObj = clone(initObj);</div><div class="line"><span class="built_in">console</span>.log(<span class="string">'拷贝的对象属性方法'</span>)</div><div class="line"><span class="built_in">console</span>.log(newObj.b);</div><div class="line"><span class="built_in">console</span>.log(newObj.c);</div><div class="line"><span class="built_in">console</span>.log(newObj.d);</div><div class="line">newObj.a=<span class="string">"xiaofangkuai"</span>;</div><div class="line">newObj.b.a = <span class="string">"hhardyy"</span>;</div><div class="line">newObj.c = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</div><div class="line">newObj.d = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</div><div class="line">    alert(<span class="string">"hhardyy1"</span>);</div><div class="line">&#125;;</div><div class="line"><span class="built_in">console</span>.log(<span class="string">'初始的对象属性方法'</span>)</div><div class="line"><span class="built_in">console</span>.log(initObj.b);</div><div class="line"><span class="built_in">console</span>.log(initObj.c);</div><div class="line"><span class="built_in">console</span>.log(initObj.d);</div><div class="line"><span class="built_in">console</span>.log(<span class="string">'区别是initObj下面的b对象下面a没有被拷贝，也就是说只拷贝了一层'</span>)</div></pre></td></tr></table></figure></p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/deepcopy/1.JPG" alt="console" title="">
                </div>
                <div class="image-caption">console</div>
            </figure>
<p>ES6提供了一个新函数用于浅拷贝Object.assign()，可以处理一层的深度拷贝，可以把任意多个的源对象自身的可枚举属性拷贝给目标对象，然后返回目标对象。拷贝的是对象的属性的引用，而不是对象本身。<br><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign" target="_blank" rel="external">文档地址</a><br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">Object</span>.assign(target, ...sources)  <span class="comment">//target=目标对象，sources=源对象，返回值等于目标对象</span></div></pre></td></tr></table></figure></p>
<p>继续上面的例子，这是一层的<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> a = &#123;</div><div class="line">name: <span class="string">"hhardyy"</span></div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> b = <span class="built_in">Object</span>.assign(&#123;&#125;, a);</div><div class="line">b.name=<span class="string">"xiaofangkuai"</span></div><div class="line"><span class="built_in">console</span>.log(a.name)<span class="comment">//hhardyy,证明a.name没有被改动</span></div></pre></td></tr></table></figure></p>
<p>继续上面的例子<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> a = &#123;</div><div class="line">name: &#123;</div><div class="line">    <span class="string">'firstname'</span>:<span class="string">'xiao'</span>,</div><div class="line">     <span class="string">'lastname'</span>:&#123;</div><div class="line">        age:<span class="number">20</span></div><div class="line">     &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> b = <span class="built_in">Object</span>.assign(&#123;&#125;, a);</div><div class="line">b.name.firstname=<span class="string">"hhardyy"</span></div><div class="line">b.name.lastname.age=<span class="number">19</span></div><div class="line"><span class="built_in">console</span>.log(b.name)</div><div class="line"><span class="built_in">console</span>.log(a.name)</div></pre></td></tr></table></figure></p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/deepcopy/2.JPG" alt="age出毛病了" title="">
                </div>
                <div class="image-caption">age出毛病了</div>
            </figure>
<h3 id="深拷贝"><a href="#深拷贝" class="headerlink" title="深拷贝"></a>深拷贝</h3><p>obj1要完全复制obj2的属性方法，同时obj1要是改变不会影响obj2的属性方法，同时满足多层拷贝</p>
<h4 id="对象只有一层的话，可以用ES6的Object-assign-，例子还是上面那个"><a href="#对象只有一层的话，可以用ES6的Object-assign-，例子还是上面那个" class="headerlink" title="对象只有一层的话，可以用ES6的Object.assign()，例子还是上面那个"></a>对象只有一层的话，可以用ES6的Object.assign()，例子还是上面那个</h4><h4 id="stringify"><a href="#stringify" class="headerlink" title="stringify"></a>stringify</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> a = &#123;</div><div class="line">    name: &#123;</div><div class="line">        <span class="string">'firstname'</span>:<span class="string">'xiao'</span>,</div><div class="line">        <span class="string">'lastname'</span>:&#123;</div><div class="line">            age:<span class="number">20</span></div><div class="line">        &#125;</div><div class="line">      &#125;</div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> strA=<span class="built_in">JSON</span>.stringify(a);</div><div class="line"><span class="built_in">console</span>.log(<span class="string">'字符串的a对象:'</span>+strA)</div><div class="line"><span class="keyword">var</span> b =<span class="built_in">JSON</span>.parse(strA)</div><div class="line">b.name.firstname=<span class="string">"hhardyy"</span></div><div class="line">b.name.lastname.age=<span class="number">19</span></div><div class="line"><span class="built_in">console</span>.log(b)</div><div class="line"><span class="built_in">console</span>.log(a)</div></pre></td></tr></table></figure>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/deepcopy/3.JPG" alt="a对象没有被改到" title="">
                </div>
                <div class="image-caption">a对象没有被改到</div>
            </figure>
<p>这种深拷贝不用每层递归，也比较简单，但是这种方法也有不少坏处，IE6、7不兼容，兼容的方法也简单，勉强用evel或者去<a href="http://www.json.org/" target="_blank" rel="external">json的官网</a>下载json类下面<br>的json2.js，然后引入,就可以兼容了。同时这种方法会抛弃对象的constructor。也就是深拷贝之后，不管这个对象原来的构造函数是什么，在深拷贝之后都会变成Object。也就是说<br>它会干掉原来对象里头的构造函数，所以有undefined和function会被除掉，只有可以转成JSON格式的对象才可以这样用，像function没办法转成JSON。还是那个例子<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> a = &#123;</div><div class="line">    name: &#123;</div><div class="line">        <span class="string">'firstname'</span>:<span class="string">'xiao'</span>,</div><div class="line">        <span class="string">'lastname'</span>:&#123;</div><div class="line">            age:<span class="number">20</span></div><div class="line">        &#125;</div><div class="line">      &#125;,</div><div class="line">      func()&#123;</div><div class="line">          <span class="built_in">console</span>.log(<span class="string">'hhardyy'</span>)</div><div class="line">      &#125;</div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> strA=<span class="built_in">JSON</span>.stringify(a);</div><div class="line"><span class="keyword">var</span> b =<span class="built_in">JSON</span>.parse(strA)</div><div class="line"><span class="built_in">console</span>.log(<span class="string">"console.log(typeof a.func):"</span>+<span class="keyword">typeof</span> a.func)</div><div class="line"><span class="built_in">console</span>.log(<span class="string">"console.log(typeof b.func):"</span>+<span class="keyword">typeof</span> b.func)</div></pre></td></tr></table></figure></p>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/deepcopy/4.JPG" alt="b.func被干掉了" title="">
                </div>
                <div class="image-caption">b.func被干掉了</div>
            </figure>
<p>stringify的缺点就是：无法实现对函数、RegExp等特殊对象的克隆，会抛弃对象的construct，所有的构造函数会指Object，有循环引用，会报错</p>
<h4 id="递归拷贝"><a href="#递归拷贝" class="headerlink" title="递归拷贝"></a>递归拷贝</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> a = &#123;</div><div class="line">    name: &#123;</div><div class="line">        <span class="string">'firstname'</span>:<span class="string">'xiao'</span>,</div><div class="line">        <span class="string">'lastname'</span>:&#123;</div><div class="line">            age:<span class="number">20</span></div><div class="line">        &#125;</div><div class="line">      &#125;,</div><div class="line">      func()&#123;</div><div class="line">          <span class="built_in">console</span>.log(<span class="string">'hhardyy'</span>)</div><div class="line">      &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="keyword">var</span> b=&#123;&#125;;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">deepClone</span>(<span class="params">objA, objB</span>) </span>&#123;    </div><div class="line">  <span class="keyword">var</span> obj = objB || &#123;&#125;;    </div><div class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> objA) &#123;        </div><div class="line">    <span class="keyword">var</span> prop = objA[i];        <span class="comment">// 避免相互引用对象导致死循环</span></div><div class="line">    <span class="keyword">if</span>(prop === obj) &#123;            </div><div class="line">      <span class="keyword">continue</span>;</div><div class="line">    &#125;  </div><div class="line"></div><div class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> prop === <span class="string">'object'</span>) &#123;</div><div class="line">      obj[i] = (prop.constructor === <span class="built_in">Array</span>) ? [] : &#123;&#125;;            </div><div class="line">      <span class="built_in">arguments</span>.callee(prop, obj[i]);</div><div class="line">    &#125; <span class="keyword">else</span> &#123;</div><div class="line">      obj[i] = prop;</div><div class="line">    &#125;</div><div class="line">  &#125;    </div><div class="line">  <span class="keyword">return</span> obj;</div><div class="line">&#125;</div><div class="line"></div><div class="line">deepClone(a, b);</div><div class="line"><span class="built_in">console</span>.log(a);</div><div class="line"><span class="built_in">console</span>.log(b);</div></pre></td></tr></table></figure>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="/images/deepcopy/5.JPG" alt="b.func被干掉了" title="">
                </div>
                <div class="image-caption">b.func被干掉了</div>
            </figure>
<h4 id="JQ的-extend"><a href="#JQ的-extend" class="headerlink" title="JQ的$.extend"></a>JQ的$.extend</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> $ = <span class="built_in">require</span>(<span class="string">'jquery'</span>);</div><div class="line"><span class="keyword">var</span> a = &#123;</div><div class="line">    name: &#123;</div><div class="line">        <span class="string">'firstname'</span>:<span class="string">'xiao'</span>,</div><div class="line">        <span class="string">'lastname'</span>:&#123;</div><div class="line">            age:<span class="number">20</span></div><div class="line">        &#125;</div><div class="line">      &#125;,</div><div class="line">      func()&#123;</div><div class="line">          <span class="built_in">console</span>.log(<span class="string">'hhardyy'</span>)</div><div class="line">      &#125;</div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> b = $.extend(<span class="literal">true</span>, &#123;&#125;, a);</div></pre></td></tr></table></figure>
<h4 id="函数库lodash的-cloneDeep"><a href="#函数库lodash的-cloneDeep" class="headerlink" title="函数库lodash的_.cloneDeep"></a>函数库lodash的_.cloneDeep</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> _ = <span class="built_in">require</span>(<span class="string">'lodash'</span>);</div><div class="line"><span class="keyword">var</span> $ = <span class="built_in">require</span>(<span class="string">'jquery'</span>);</div><div class="line"><span class="keyword">var</span> a = &#123;</div><div class="line">    name: &#123;</div><div class="line">        <span class="string">'firstname'</span>:<span class="string">'xiao'</span>,</div><div class="line">        <span class="string">'lastname'</span>:&#123;</div><div class="line">            age:<span class="number">20</span></div><div class="line">        &#125;</div><div class="line">      &#125;,</div><div class="line">      func()&#123;</div><div class="line">          <span class="built_in">console</span>.log(<span class="string">'hhardyy'</span>)</div><div class="line">      &#125;</div><div class="line">&#125;</div><div class="line"><span class="keyword">var</span> b = _.cloneDeep(a);</div></pre></td></tr></table></figure>
<p>这个用起来简单，而且性能也不错</p>
<h3 id="封装一个对象拷贝的方法"><a href="#封装一个对象拷贝的方法" class="headerlink" title="封装一个对象拷贝的方法"></a>封装一个对象拷贝的方法</h3><p>假如obj2要拷贝obj1里面的属性和方法可以用<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">HexTend</span>(<span class="params">obj1,obj2</span>)</span>&#123;</div><div class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> attr <span class="keyword">in</span> obj1)&#123;</div><div class="line">        obj2[attr]=obj1[attr];</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> obj2;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>也可以简单点b={…a}或者Object.assign(b,a),如果非对象参数出现在源对象的位置，那么这些参数都会转成对象，如果无法转成对象，就会跳过。也就是undefined和null不放<br>在第一个参数，就不会报错。其他类型的值比如number、string、boolean不在第一个参数，也不会报错。但是字符串会以数组形式拷贝入目标对象，其他值没效果。</p>
<blockquote>
<p>注意：Object.assign方法实行的是浅拷贝，如果源对象某个属性的值是对象，则目标对象拷贝到的是这个对象的引用。</p>
</blockquote>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2020-01-13T15:30:26.578Z" itemprop="dateUpdated">2020-01-13 23:30:26</time>
</span><br>


        
        谢谢浏览，我会继续努力的，示例：<a href="/2018/07/10/对象深拷贝与浅拷贝/" target="_blank" rel="external">http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/</a>
        
    </div>
    <footer>
        <a href="http://yoursite.com">
            <img src="/img/avatar.jpg" alt="BingZhenhuang">
            BingZhenhuang
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/ES6-Object-assign/">ES6-Object.assign()</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JQ的-extend/">JQ的$.extend</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/stringify/">stringify</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/函数库lodash的-cloneDeep/">函数库lodash的_.cloneDeep</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/深拷贝与浅拷贝/">深拷贝与浅拷贝</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/递归拷贝/">递归拷贝</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/&title=《对象深拷贝与浅拷贝》 — 小方块 - hhardyy.com&pic=http://yoursite.com/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/&title=《对象深拷贝与浅拷贝》 — 小方块 - hhardyy.com&source=偶然与道友产生了深浅拷贝的异议，所以赶紧补一补习，需要的你也可以看看
" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《对象深拷贝与浅拷贝》 — 小方块 - hhardyy.com&url=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/&via=http://yoursite.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2018/07/22/BMap-is-not-defined？BMap初始化报错爆红/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">&#39;BMap&#39; is not defined？BMap初始化爆红</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2018/07/08/面向对象的艺术/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">面向对象的艺术</h4>
      </a>
    </div>
  
</nav>



    














</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        🤠 请我喝可乐！
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content" style="width:50%">
        
        <div class="reward-code" style="text-align:center">
            <div style="width:300px;margin:0px auto;">
               <img id="rewardCode" style="width:50%;height:60%;display:block; margin:0px auto;" src="/img/alipay.jpg" alt="支付宝打赏二维码">
               <span style="display:inline-block; margin-bottom:20px;">0.88(支付宝 aliPay)</span>
               <img id="rewardCode" style="width:50%;height:60%;display:block; margin:0px auto;" src="/img/wechat.jpg" alt="微信打赏二维码">
               <span style="display:inline-block;">0.88(微信 weChat)</span>
            </div>
        </div>
    </div>
</div>



</div>

        <script>
!function(e,t,a){function n(){c(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"),o(),r()}function r(){for(var e=0;e<d.length;e++)d[e].alpha<=0?(t.body.removeChild(d[e].el),d.splice(e,1)):(d[e].y--,d[e].scale+=.004,d[e].alpha-=.013,d[e].el.style.cssText="left:"+d[e].x+"px;top:"+d[e].y+"px;opacity:"+d[e].alpha+";transform:scale("+d[e].scale+","+d[e].scale+") rotate(45deg);background:"+d[e].color+";z-index:99999");requestAnimationFrame(r)}function o(){var t="function"==typeof e.onclick&&e.onclick;e.onclick=function(e){t&&t(),i(e)}}function i(e){var a=t.createElement("div");a.className="heart",d.push({el:a,x:e.clientX-5,y:e.clientY-5,scale:1,alpha:1,color:s()}),t.body.appendChild(a)}function c(e){var a=t.createElement("style");a.type="text/css";try{a.appendChild(t.createTextNode(e))}catch(t){a.styleSheet.cssText=e}t.getElementsByTagName("head")[0].appendChild(a)}function s(){return"rgb("+~~(255*Math.random())+","+~~(255*Math.random())+","+~~(255*Math.random())+")"}var d=[];e.requestAnimationFrame=function(){return e.requestAnimationFrame||e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)}}(),n()}(window,document);
</script>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<script>
    function secondToDate(second) {
        if (!second) {
            return 0;
        }
        var time = new Array(0, 0, 0, 0, 0);
        if (second >= 365 * 24 * 3600) {
            time[0] = parseInt(second / (365 * 24 * 3600));
            second %= 365 * 24 * 3600;
        }
        if (second >= 24 * 3600) {
            time[1] = parseInt(second / (24 * 3600));
            second %= 24 * 3600;
        }
        if (second >= 3600) {
            time[2] = parseInt(second / 3600);
            second %= 3600;
        }
        if (second >= 60) {
            time[3] = parseInt(second / 60);
            second %= 60;
        }
        if (second > 0) {
            time[4] = second;
        }
        return time;
    }</script>
<script type="text/javascript" language="javascript">
    function setTime() {
        var create_time = Math.round(new Date(Date.UTC(2017, 08, 18, 11, 42, 23)).getTime() / 1000);
        var timestamp = Math.round((new Date().getTime() + 8 * 60 * 60 * 1000) / 1000);
        currentTime = secondToDate((timestamp - create_time));
        currentTimeHtml = 'Running：' + currentTime[0] + '年 ' + currentTime[1] + '天 '
                + currentTime[2] + '时 ' + currentTime[3] + '分 ' + currentTime[4]
                + '秒';
        document.getElementById("htmer_time").innerHTML = currentTimeHtml;
    }    setInterval(setTime, 1000);
</script>
<footer class="footer">
    <div class="top">
        

        <p>
          <span id="busuanzi_container_page_pv">
             [&nbsp;浏览量：&nbsp;<span id="busuanzi_value_page_pv"></span>&nbsp;]
          </span>
        </p>
    </div>
    <div class="bottom">
        <p>
        <span>BingZhenhuang &copy; 2017 - 2020</span>
            <span>
                
                Power by <a href="https://hhardyy.github.io/" target="_blank">zhen On August 8</a> 
            </span>
            <span id="htmer_time" "></span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/&title=《对象深拷贝与浅拷贝》 — 小方块 - hhardyy.com&pic=http://yoursite.com/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/&title=《对象深拷贝与浅拷贝》 — 小方块 - hhardyy.com&source=偶然与道友产生了深浅拷贝的异议，所以赶紧补一补习，需要的你也可以看看
" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《对象深拷贝与浅拷贝》 — 小方块 - hhardyy.com&url=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/&via=http://yoursite.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://yoursite.com/2018/07/10/对象深拷贝与浅拷贝/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>








<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '(•‾̑⌣‾̑•)✧˖°回来看我';
            clearTimeout(titleTime);
        } else {
            document.title = '(゜-゜)つロ欢迎回来';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
